package com.team11.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.team11.server.config.SplicingConfig;
import com.team11.server.mapper.*;
import com.team11.server.pojo.*;
import com.team11.server.pojo.dto.RespBean;
import com.team11.server.pojo.dto.RespPageBean;
import com.team11.server.pojo.dto.vo.AddLeave;
import com.team11.server.pojo.dto.vo.Leave;
import com.team11.server.service.ILInformationService;
import com.team11.server.util.file.GetFilesUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author mahongtao
 * @since 2021-06-17
 */
@Service
public class LInformationServiceImpl extends ServiceImpl<LInformationMapper, LInformation> implements ILInformationService {
    @Resource
    private LInformationMapper lInformationMapper;

    @Resource
    private SInformationMapper sInformationMapper;

    @Resource
    private CFilesMapper cFilesMapper;

    @Resource
    private AInformationMapper aInformationMapper;

    @Resource
    private LRecordMapper lRecordMapper;


    /**
     * 获取请假管理的记录（分页）
     *
     * @param currentPage     s
     * @param size            s
     * @param informationLIst s
     * @param startTime       s
     * @param endTime         s
     * @return s
     */
    @Override
    public RespPageBean getLInformationByPage(Integer currentPage, Integer size, InformationLIst informationLIst,
                                              LocalDate startTime, LocalDate endTime) {
        //开启分页
        Page<InformationLIst> page = new Page<>(currentPage, size);
        IPage<InformationLIst> lInformationIPage = lInformationMapper.getLInformationLIstByPage(page,
                informationLIst, startTime, endTime);
        return new RespPageBean(lInformationIPage.getTotal(), lInformationIPage.getRecords());
    }

    /**
     * 获取请假原因
     *
     * @return s
     */
    @Override
    public Object getReason() {
        List<LInformation> items = lInformationMapper.selectList(null);
        List<String> list = items.stream().map(LInformation::getLReason).collect(Collectors.toList());
        return new ArrayList<>(new TreeSet<>(list));
    }

    /**
     * 获取所有的审批状态
     *
     * @return s
     */
    @Override
    public Object getStatus() {
        List<LInformation> list = lInformationMapper.selectList(null);
        return list.stream().map(LInformation::getLStatus).collect(Collectors.toList());
    }

    /**
     * 审批请假记录
     *
     * @param lId    s
     * @param status s
     * @return s
     */
    @Override
    public RespBean approval(List<Integer> lId, Integer status, String failReason) {
        LInformation lInformation = new LInformation();
        LRecord lRecord = new LRecord();
        for (Integer integer : lId) {
            if (integer == null) {
                return RespBean.error("请假id不能为空");
            }
            lInformation.setLStatus(status);
            lInformation.setLId(integer);
            if (status == 1) {
                LocalDateTime dateTime = LocalDateTime.now();
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                String Time = dateTime.format(formatter);
                LocalDateTime localDateTime = LocalDateTime.parse(Time, formatter);
                System.out.println(localDateTime);
                lRecord.setLTime(localDateTime);
                lRecordMapper.updateById(lRecord);
                lInformationMapper.updateById(lInformation);
            } else if (status == 0) {
                LocalDateTime dateTime = LocalDateTime.now();
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                String Time = dateTime.format(formatter);
                LocalDateTime localDateTime = LocalDateTime.parse(Time, formatter);
                System.out.println(localDateTime);
                lRecord.setLTime(localDateTime);
                lRecordMapper.updateById(lRecord);
                lInformation.setLFailReason(failReason);
                lInformationMapper.updateById(lInformation);
            }
        }
        return RespBean.success("审核成功!");
    }

    /**
     * 根据学生id获取请假详情
     *
     * @param sid s
     * @return s
     */
    @Override
    public List getdetail(Integer sid) {
        return lInformationMapper.getdetail(sid);
    }


    /**
     * 学生端：请假管理
     *
     * @param currentPage s
     * @param size        s
     * @param leave       s
     * @return s
     */
    @Override
    public RespPageBean getStudentLInformation(Integer currentPage, Integer size, Integer sNumber,
                                               Leave leave) {
        Integer count = sInformationMapper.selectCount(new QueryWrapper<SInformation>().eq("s_id", sNumber));
        if (count == 0) {
            List<String> list = new ArrayList<>();
            String a = "该用户不存在!";
            list.add(a);
            return new RespPageBean(0L, list);
        }
        Integer sid = sInformationMapper.selectOne(new QueryWrapper<SInformation>().eq("s_id", sNumber)).getSid();
        Integer sid1 = lInformationMapper.selectCount(new QueryWrapper<LInformation>().eq("sid", sid));
        if (sid1 == 0) {
            return new RespPageBean(0L, null);
        }
        IPage<List<Map<String, Object>>> page = new Page<>(currentPage, size);
        IPage<List<Map<String, Object>>> studentLInformation = lInformationMapper.getStudentLInformation(page, sid, leave);
        return new RespPageBean(studentLInformation.getTotal(), studentLInformation.getRecords());
    }


//    /**
//     * 进入新增/编辑页面
//     *
//     * @param sid
//     * @return
//     */
//    @Override
//    public List<Map<String, Object>> openLeave(Integer sid, Integer lId) {
//        Integer count1 = sInformationMapper.selectCount(new QueryWrapper<SInformation>().eq("sid", sid));
//        if (count1 == 0) {
//            List list1 = new ArrayList();
//            String a = "该学员不存在!";
//            list1.add(a);
//            return list1;
//        }
//        List list = new ArrayList<>();
//        Map map = lInformationMapper.getStudentDetails(sid);
//        list.add(map);
//        if (lId != null) {
//            Integer count = lInformationMapper.selectCount(new QueryWrapper<LInformation>().eq("l_id", lId).eq("sid", sid));
//            if (count == 0) {
//                List list1 = new ArrayList();
//                String a = "请输入与lId对应的学生id";
//                list1.add(a);
//                return list1;
//            }
//            Map map1 = lInformationMapper.getLeaveDetails(lId);
//            Integer l_file = (Integer) map1.get("l_file");
//            String cFName = null;
//            String cFile = null;
//            if (l_file != null) {
//                cFName = cFilesMapper.selectOne(new QueryWrapper<CFiles>().eq("c_f_id", l_file)).getCFName();
//                cFile = cFilesMapper.selectOne(new QueryWrapper<CFiles>().eq("c_f_id", l_file)).getCFile();
//            }
//            map1.put("cFName", cFName);
//            map1.put("cFile", cFile);
//            list.add(map1);
//            List<Map<String,Object>> list1  = lRecordMapper.getLRecord(lId);
//            list.add(list1);
//
//        }
//        return list;
//    }

    /**
     * 进入编辑页面(详情页)
     *
     * @param lId s
     * @return s
     */
    @Override
    public List<Map<String, Object>> openLeave(Integer lId) {
        Integer count = lInformationMapper.selectCount(new QueryWrapper<LInformation>().eq("l_id", lId));
        if (count == 0) {
            List list1 = new ArrayList<>();
            String a = "lId不存在";
            list1.add(a);
            return list1;
        }
        List list = new ArrayList<>();
        //获取学生信息
        Integer sid = lInformationMapper.selectOne(new QueryWrapper<LInformation>().eq("l_id", lId)).getSid();
        Map map = lInformationMapper.getStudentDetails(sid);
        list.add(map);
        //获取请假表信息
        Map map1 = lInformationMapper.getLeaveDetails(lId);
        Integer l_file = (Integer) map1.get("l_file");
        String cFName = null;
        String cFile = null;
        if (l_file != null) {
            cFName = cFilesMapper.selectOne(new QueryWrapper<CFiles>().eq("c_f_id", l_file)).getCFName();
            cFile = cFilesMapper.selectOne(new QueryWrapper<CFiles>().eq("c_f_id", l_file)).getCFile();
        }
        map1.put("cFName", cFName);
        map1.put("cFile", cFile);
        list.add(map1);
        //获取操作记录信息
        List<Map<String, Object>> list1 = lRecordMapper.getLRecord(lId);
        list.add(list1);

        return list;
    }

    /**
     * 学生端：请假管理：新增请假
     *
     * @param sid
     * @param files
     * @param request
     * @return
     */
    @Override
    public RespBean addLeave(Integer sid, AddLeave addLeave, MultipartFile[] files, HttpServletRequest request) {
        Integer count = sInformationMapper.selectCount(new QueryWrapper<SInformation>().eq("sid", sid));
        if (count == 0) {
            return RespBean.success("该学员不存在");
        }
        LInformation lInformation = new LInformation();
        lInformation.setLTheme(addLeave.getLTheme());
        lInformation.setLBegin(addLeave.getLBegin());
        lInformation.setLEnd(addLeave.getLEnd());
        lInformation.setLReason(addLeave.getLReason());
        lInformation.setLJtReason(addLeave.getLJtReason());
        lInformation.setLDate(LocalDateTime.now());
        lInformation.setSid(sid);
        lInformation.setLStatus(2);

        if (lInformationMapper.insert(lInformation) == 1) {
            LRecord lRecord = new LRecord();
            lRecord.setLId(lInformation.getLId());
            lRecord.setTId(addLeave.getTId());
            lRecordMapper.insert(lRecord);
            //上传文件，并保存路径到数据库
            if (files != null) {
                CFiles cFiles = new CFiles();
                List list1 = new ArrayList();
                List list2 = new ArrayList();
                List list3 = GetFilesUtil.getFiles(files, request);
                list1.add(list3.get(0));
                list2.add(list3.get(1));
                cFiles.setCFName(SplicingConfig.Splicing(list1));
                cFiles.setCFile(SplicingConfig.Splicing(list2));

                cFiles.setCFType(3);
                cFiles.setSid(sid);
                System.out.println(lInformation.getLId());
                cFiles.setQId(lInformation.getLId());

                if (cFilesMapper.insert(cFiles) == 1) {
                    LInformation lInformation1 = new LInformation();
                    System.out.println(cFiles.getCFId());
                    lInformation1.setLFile(cFiles.getCFId());
                    lInformation1.setLId(lInformation.getLId());
                    if (lInformationMapper.updateById(lInformation1) == 1) {
                        return RespBean.success("新增请假成功!");
                    }
                }
            }
            return RespBean.success("新增请假成功!");
        }
        return RespBean.error("新增请假失败!");
    }

    /**
     * 编辑请假
     *
     * @param lId
     * @param addLeave
     * @param files
     * @param request
     * @return
     */
    @Override
    public RespBean updateLeave(Integer lId, AddLeave addLeave, MultipartFile[] files, HttpServletRequest request) {
        Integer count = lInformationMapper.selectCount(new QueryWrapper<LInformation>().eq("l_id", lId));
        if (count == 0) {
            return RespBean.success("lId不存在!");
        }
        LInformation lInformation1 = lInformationMapper.selectOne(new QueryWrapper<LInformation>().eq("l_id", lId));
        if (lInformation1.getLStatus() == 1) {
            return RespBean.error("您的请假申请已经通过，不能进行修改!");
        }
        if (lInformation1.getSid() != null) {
            Integer sid = lInformation1.getSid();
            LInformation lInformation = new LInformation();
            lInformation.setLTheme(addLeave.getLTheme());
            lInformation.setLBegin(addLeave.getLBegin());
            lInformation.setLEnd(addLeave.getLEnd());
            lInformation.setLReason(addLeave.getLReason());
            lInformation.setLJtReason(addLeave.getLJtReason());
            lInformation.setLDate(LocalDateTime.now());
            lInformation.setSid(sid);
            lInformation.setLStatus(2);
            lInformation.setLId(lId);
            //附件
            if (lInformationMapper.updateById(lInformation) == 1) {
                LRecord lRecord = new LRecord();
                lRecord.setLId(lInformation.getLId());
                lRecord.setTId(addLeave.getTId());
                lRecordMapper.insert(lRecord);

                //上传文件，并保存路径到数据库
                if (files != null) {
                    CFiles cFiles = new CFiles();
                    List list1 = new ArrayList();
                    List list2 = new ArrayList();
                    List list3 = GetFilesUtil.getFiles(files, request);
                    list1.add(list3.get(0));
                    list2.add(list3.get(1));

                    cFiles.setCFName(SplicingConfig.Splicing(list1));
                    cFiles.setCFile(SplicingConfig.Splicing(list2));
                    cFiles.setCFType(3);
                    cFiles.setSid(sid);
                    cFiles.setQId(lId);
                    //上传附件信息到数据库
                    if (lInformation1.getLFile() != null) {
                        cFiles.setCFId(lInformation1.getLFile());
                        if (cFilesMapper.updateById(cFiles) == 1) {
                            return RespBean.success("修改请假成功!");
                        }
                    } else {
                        if (cFilesMapper.insert(cFiles) == 1) {
                            LInformation lInformation2 = new LInformation();
                            lInformation2.setLFile(cFiles.getCFId());
                            lInformation2.setLId(lId);
                            if (lInformationMapper.updateById(lInformation2) == 1) {
                                return RespBean.success("修改请假成功!");
                            }
                        }
                    }
                }
                return RespBean.success("修改请假成功!");
            }

        }
        return RespBean.error("修改请假失败!");
    }


}
